package juc.cas;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/*
* 原子数组
* */
public class Test10 {
    public static void main(String[] args) {
           int[]intArr=new int[10];
           demo(
                   ()->intArr,
                   (arr)->arr.length,
                   (arr,index)->arr[index]++,
                   (arr)-> System.out.println(Arrays.toString(arr))
           );
        AtomicIntegerArray atomicIntegerArray=new AtomicIntegerArray(10);
        demo(
                ()->atomicIntegerArray,
                (arr)->arr.length(),
                (arr,index)->arr.addAndGet(index,1),
                (arr)-> System.out.println(arr)
        );
    }
    public static<T> void demo(
            Supplier<T> arraySupplier,
            Function<T,Integer>lenFun,
            BiFunction<T,Integer,Integer>op,
            Consumer<T>printResult
    ){
        T array = arraySupplier.get();
        Integer len = lenFun.apply(array);
        List<Thread>threads=new ArrayList<>(len);
        for (int i = 0; i <len ; i++) {
            Thread t = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    op.apply(array, j % len);
                }
            });
            threads.add(t);
            t.start();
        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        printResult.accept(array);
    }
}
